/*
 * @Author: sunkai@xinxinapp.cn
 * @Date: 2020-12-25 01:24:00
 * @LastEditTime: 2021-06-28 13:55:56
 * @LastEditors: sunkai@xinxinapp.cn
 * @Description: 
 * @FilePath: /fed-e-task-05-03/middleware/auth.js
 */
const { verify } = require('../util/jwt')
const { jwtSecret } = require('../config/config.default')
const { User } = require('../model')

module.exports = async (req, res, next) => {
  // 从请求头获取 token 数据
  let token = req.headers['authorization']
  token = token
    ? token.split('Bearer ')[1]
    : null

  if (!token) {
    return res.status(401).end()
  }

  try {
    const decodedToken = await verify(token, jwtSecret)
    req.user = await User.findById(decodedToken.userId)
    next()
  } catch (err) {
    return res.status(401).end()
  }
}
